package com.cube.share.base.function;

import com.cube.share.base.utils.IAssert;
import org.springframework.lang.Nullable;

import java.util.function.Supplier;

/**
 * @author poker.li
 * @date 2021/7/21 16:54
 * <p>
 * 单例对象提供类
 */
public class SingletonSupplier<T> implements Supplier<T> {

    @Nullable
    private final Supplier<? extends T> instanceSupplier;

    @Nullable
    private final Supplier<? extends T> defaultSupplier;

    @Nullable
    private volatile T singletonInstance;

    public SingletonSupplier(@Nullable T instance, Supplier<? extends T> defaultSupplier) {
        this.instanceSupplier = null;
        this.defaultSupplier = defaultSupplier;
        this.singletonInstance = instance;
    }

    public SingletonSupplier(@Nullable Supplier<? extends T> instanceSupplier, Supplier<? extends T> defaultSupplier) {
        this.instanceSupplier = instanceSupplier;
        this.defaultSupplier = defaultSupplier;
    }

    private SingletonSupplier(Supplier<? extends T> supplier) {
        this.instanceSupplier = supplier;
        this.defaultSupplier = null;
    }

    private SingletonSupplier(T instance) {
        this.singletonInstance = instance;
        this.instanceSupplier = null;
        this.defaultSupplier = null;
    }

    /**
     * 获取单例对象
     *
     * @return 单例对象, 可能是null
     */
    @Override
    public T get() {
        //double check
        if (this.singletonInstance == null) {
            synchronized (this) {
                if (this.singletonInstance == null) {
                    if (this.instanceSupplier != null) {
                        this.singletonInstance = instanceSupplier.get();
                    }
                    if (this.singletonInstance == null && this.defaultSupplier != null) {
                        this.singletonInstance = this.defaultSupplier.get();
                    }
                }
            }
        }
        return this.singletonInstance;
    }

    /**
     * 获取单例对象
     *
     * @return 单例对象, 如果为null则抛出异常
     */
    public T obtain() {
        T instance = get();
        IAssert.state(instance != null, "No instance from Supplier");
        return instance;
    }

    public static <T> SingletonSupplier<T> of(T instance) {
        return new SingletonSupplier<>(instance);
    }

    @Nullable
    public static <T> SingletonSupplier<T> ofNullable(@Nullable T instance) {
        return (instance != null ? new SingletonSupplier<>(instance) : null);
    }

    public static <T> SingletonSupplier<T> of(Supplier<T> supplier) {
        return new SingletonSupplier<>(supplier);
    }

    @Nullable
    public static <T> SingletonSupplier<T> ofNullable(@Nullable Supplier<T> supplier) {
        return (supplier != null ? new SingletonSupplier<>(supplier) : null);
    }
}
